package org.computate.form.item;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


public class FormGroup extends FormItem {
	private String label;
	private List<FormItem> children = new ArrayList<FormItem>();
	private Integer columns = null;
	private Class<?> c = null;
	private String text;
	
	public FormGroup(Class<?> c) {
		this.c = c;
	}

	public List<FormItem> getChildren() {
		return children;
	}


	public FormGroup setChildren(List<FormItem> children) {
		this.children = children;
		
		for(FormItem child : children) {
			child.setParent(this);
		}
		
		return this;
	}
	
	public FormGroup addHiddenItem(FormItem child) {
		this.children.add(child);
		child.setParent(this);
		
		return this;
	}
	
	public FormGroup addField(String name, String label) {
		FormField item = createField(name, label);
		
		this.children.add(item);
		item.setParent(this);
		
		return this;
	}
	
	public FormGroup add(FormItem item) {
		if(item != null) {
			this.children.add(item);
			item.setParent(this);
		}
		
		return this;
	}
	
	protected FormField createField(String name, String label) {
		FormField item = new FormField();
		
		try {
			Field field = this.c.getDeclaredField(name);
			Class<?> fieldClass = field.getType();
			item.setC(fieldClass);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		item.setName(name);
		item.setLabel(label);
		
		return item;
	}


	public String getLabel() {
		return label;
	}


	public FormGroup setLabel(String label) {
		this.label = label;
		
		return this;
	}


	public Integer getColumns() {
		return columns;
	}


	public FormGroup setColumns(Integer columns) {
		this.columns = columns;
		
		return this;
	}

	public String getText() {
		return text;
	}

	public FormGroup setText(String text) {
		this.text = text;
		
		return this;
	}
}
